package com.health.trans.util;

import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author nqlz
 */
public class BatchThreadPool {

    public static ThreadPoolExecutor POOL;
    public static ThreadPoolTaskExecutor taskExecutor;

    @Bean("myTaskExecutor")
    public TaskExecutor taskExecutor() {
        AtomicInteger tag = new AtomicInteger(1);
        ThreadFactory namedFactory = (Runnable r) -> {
            Thread thread = new Thread(r);
            thread.setName("mysql-to-es-" + tag.getAndIncrement());
            return thread;
        };
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadFactory(namedFactory);
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(500);
        // 设置线程池中任务的等待时间，若超过等待时间仍未销毁则强制销毁，以确保应用最后能够被关闭，而不是阻塞住
        executor.setAwaitTerminationSeconds(60);
        // 设置拒绝策略，当线程池阻塞队列已满时对新任务的处理。调节机制，即饱和时回退主线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        BatchThreadPool.POOL = executor.getThreadPoolExecutor();
        BatchThreadPool.taskExecutor = executor;
        return executor;
    }

}
